package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.utils.MyAssert;
import com.atguigu.spzx.manager.mapper.SysMenuMapper;
import com.atguigu.spzx.manager.service.SysMenuService;
import com.atguigu.spzx.manager.utils.MenuHelper;
import com.atguigu.spzx.model.entity.system.AuthContextUtil;
import com.atguigu.spzx.model.entity.system.SysMenu;
import com.atguigu.spzx.model.vo.system.SysMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> findNodes() {
        List<SysMenu> sysMenus = sysMenuMapper.selectAll();
        return MenuHelper.buildTree(sysMenus);
    }

    @Override
    public void save(SysMenu sysMenu) {
        sysMenuMapper.insert(sysMenu);
    }

    @Override
    public void removeById(Long id) {
        int count = sysMenuMapper.countByParentId(id);

        MyAssert.isTrue(count == 0, "存在子菜单");

        sysMenuMapper.deleteById(id);

    }

    @Override
    public void updateById(SysMenu sysMenu) {
        sysMenuMapper.updateById(sysMenu);
    }

    @Override
    public List<SysMenuVo> findUserMenuList() {
        // 获取当前登录用户的id
        Long userId = AuthContextUtil.get().getId();

        // 查询当前用户所分配的所有菜单列表
        List<SysMenu> sysMenuList = sysMenuMapper.selectListByUserId(userId);

        // 转成树状格式
        List<SysMenu> sysMenuTreeList = MenuHelper.buildTree(sysMenuList);

        // SysMenu to SysMenuVo
        return this.buildMenus(sysMenuTreeList);
    }

    private List<SysMenuVo> buildMenus(List<SysMenu> menus) {

        return menus.stream().map(
            menu -> {
                SysMenuVo sysMenuVo = new SysMenuVo();

                sysMenuVo.setTitle(menu.getTitle());
                sysMenuVo.setName(menu.getComponent());
                List<SysMenu> children = menu.getChildren();
                if (!CollectionUtils.isEmpty(children)) {
                    sysMenuVo.setChildren(buildMenus(children));
                }

                return sysMenuVo;
            }
        ).toList();
    }

}
